import { PlusCircleOutlined } from '@ant-design/icons'
import { ConfigProvider, Table, TimePicker } from 'antd'
import dayjs from 'dayjs'
import { uniqueId } from 'lodash-es'
import { useEffect, useState } from 'react'

import { companionContentOptionsListApi } from '@/api/pcs/pcsCompanionContent'
import { createCompanionFlowApi, getCompanionFlowApi, updateCompanionFlowApi } from '@/api/pcs/pcsCompanionFlow'
import AekDrawer, { PromiseThen } from '@/components/AekDrawer'
import AekForm from '@/components/AekForm'
import AekLinkButton from '@/components/AekLinkButton'
import AekSelect from '@/components/AekSelect'
import { ENABLE_STATUS_ENUM, PCS_CONTENT_AVAILABLEPOPULATION_ENUM } from '@/utils/enum'
import { requestWithTry } from '@/utils/request'

const EditDrawer = ({ row = {} }) => {
  const { id } = row
  const [form] = AekForm.useForm()
  const items = AekForm.useWatch('items', form)

  const [loading, setLoading] = useState(false)
  const [flows, setFlows] = useState([{ key: uniqueId() }])

  const getDetail = async () => {
    setLoading(true)
    const { data } = await requestWithTry(getCompanionFlowApi, { id }).finally(() => setLoading(false))

    setFlows(data.items.map(item => ({ ...item, key: uniqueId() })))
    form.setFieldsValue({
      name: data.name,
    })
  }

  useEffect(() => {
    if (id) {
      getDetail()
    }
  }, [id])

  const timeRangeFormat = 'HH:mm'

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData = [
    {
      field: 'name',
      label: '流程名称',
      col: 8,
      formItemProps: {
        rules: [{ required: true }],
      },
      component: { name: 'Input' },
    },
    {
      label: '工作流程',
      col: 24,
      component: (
        <ConfigProvider
          theme={{
            components: {
              Form: {
                itemMarginBottom: 0,
              },
            },
          }}
        >
          <Table
            rowKey='key'
            pagination={false}
            dataSource={flows}
            columns={[
              {
                key: 'timeRange',
                width: 300,
                title: (
                  <>
                    <span className='c-required'>*</span>
                    <span className='ml2px'>时间范围</span>
                  </>
                ),
                render: ({ key, startTime, endTime }) => (
                  <AekForm.Item
                    required
                    name={['items', key, 'timeRange']}
                    rules={[{ required: true, message: '请选择时间范围' }]}
                    initialValue={
                      startTime && endTime
                        ? [dayjs(startTime, timeRangeFormat), dayjs(endTime, timeRangeFormat)]
                        : undefined
                    }
                  >
                    <TimePicker.RangePicker format={timeRangeFormat} />
                  </AekForm.Item>
                ),
              },
              {
                key: 'companionContent',
                width: 300,
                title: (
                  <>
                    <span className='c-required'>*</span>
                    <span className='ml2px'>流程内容</span>
                  </>
                ),
                render: ({ key, companionContentId, companionContentName, availablePopulation }) => (
                  <AekForm.Item
                    required
                    name={['items', key, 'companionContent']}
                    rules={[{ required: true, message: '请选择流程内容' }]}
                    initialValue={
                      companionContentId
                        ? { id: String(companionContentId), content: companionContentName, availablePopulation }
                        : undefined
                    }
                  >
                    <AekSelect
                      api={companionContentOptionsListApi}
                      fieldNames={{ label: 'content' }}
                      labelInValue
                      columns={[
                        { title: '陪护内容', dataIndex: 'content' },
                        { title: '注意事项', dataIndex: 'announcement' },
                        { title: '状态', dataIndex: 'enable', enum: ENABLE_STATUS_ENUM },
                      ]}
                    />
                  </AekForm.Item>
                ),
              },
              {
                key: 'availablePopulation',
                title: '适用对象',
                render: ({ key }) => (
                  <div>
                    {PCS_CONTENT_AVAILABLEPOPULATION_ENUM.getText(items?.[key]?.companionContent?.availablePopulation)}
                  </div>
                ),
              },
              {
                key: 'operate',
                width: 100,
                title: (
                  <>
                    操作
                    <PlusCircleOutlined
                      className='ml10px c-primary'
                      onClick={() => {
                        const newFlow = {
                          key: uniqueId(),
                        }
                        setFlows([...flows, newFlow])
                      }}
                    />
                  </>
                ),
                render: ({ key }) =>
                  flows.length > 1 && (
                    <AekLinkButton danger onClick={() => setFlows(flows.filter(flow => flow.key !== key))}>
                      删除
                    </AekLinkButton>
                  ),
              },
            ]}
          />
        </ConfigProvider>
      ),
    },
  ]

  const onOk = async () => {
    const { items, ...otherValues } = await form.validateFields()
    const params = {
      id,
      ...otherValues,
      itemParameters: Object.values(items).map(item => ({
        companionContentId: item.companionContent.id,
        startTime: item.timeRange[0].format(timeRangeFormat),
        endTime: item.timeRange[1].format(timeRangeFormat),
      })),
    }
    await requestWithTry(id ? updateCompanionFlowApi : createCompanionFlowApi, params)
  }
  return (
    <AekDrawer title={id ? '编辑' : '新增'} width={1000} onOk={onOk} loading={loading}>
      <AekForm form={form} formData={formData} />
    </AekDrawer>
  )
}

EditDrawer.PromiseThen = PromiseThen

export default EditDrawer
